package com.ls.lserp.modules.trade.service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ls.lserp.common.persistence.Page;
import com.ls.lserp.common.service.CrudService;
import com.ls.lserp.common.utils.CollectionsUtils;
import com.ls.lserp.common.utils.ResourcesUtil;
import com.ls.lserp.common.utils.StringUtils;
import com.ls.lserp.dbaccess.Dao.ExchangeFormEntityMapper;
import com.ls.lserp.dbaccess.Dao.PackageCustomEntityMapper;
import com.ls.lserp.dbaccess.Dao.ShippingFormEntityMapper;
import com.ls.lserp.dbaccess.Entity.ExchangeFormEntity;
import com.ls.lserp.dbaccess.Entity.PackageCustomEntity;
import com.ls.lserp.modules.order.entity.AuditInfo;
import com.ls.lserp.modules.order.entity.Order;
import com.ls.lserp.modules.sys.utils.SequenceUtil;
import com.ls.lserp.modules.sys.utils.UserUtils;
import com.ls.lserp.modules.trade.dao.BookingOrdersDao;
import com.ls.lserp.modules.trade.dao.CustomEnchaseDao;
import com.ls.lserp.modules.order.dao.AuditInfoDao;
import com.ls.lserp.modules.order.dao.OrderDao;
import com.ls.lserp.modules.trade.entity.BookingOrders;
import com.ls.lserp.modules.trade.entity.ConsignmentNote;
import com.ls.lserp.modules.trade.entity.CustomEnchase;
import com.ls.lserp.modules.trade.entity.Settlement;



@Service
@Transactional(readOnly = false)
public class ConsignmentNoteService extends CrudService<ShippingFormEntityMapper, ConsignmentNote>{
	
	private static final String FORM_ID = null;
	 
	@Autowired
		private ShippingFormEntityMapper shippingFormEntityMapper;
	@Autowired
		private PackageCustomEntityMapper packageCustomEntityMapper;
	@Autowired
    	private ExchangeFormEntityMapper exchangeFormEntityMapper;
	@Autowired
		private CustomEnchaseDao customEnchaseDao;
	@Autowired
		private OrderDao orderDao;
	// 审核表
	@Autowired
		private AuditInfoDao  auditInfoDao;
	 
	public Page<ConsignmentNote> findList(Page<ConsignmentNote> page, ConsignmentNote consignmentNote) {
				// tab页分，检索条件设定(0:全部,1:已删除)
				int tabFlg = consignmentNote.getTabPageStatus();
				consignmentNote.setBookingOrdersDelFlg(BookingOrders.DEL_FLAG_NORMAL);
				if (tabFlg == 1) {
					consignmentNote.setFormStatus("0");
				}else if(tabFlg == 2){
					consignmentNote.setFormStatus("1");
				}else if(tabFlg == 3){
					consignmentNote.setBookingOrdersDelFlg(BookingOrders.DEL_FLAG_DELETE);
				}
		
				 // 生成数据权限过滤条件（dsf为dataScopeFilter的简写，在xml中使用 ${sqlMap.dsf}调用权限SQL）
		        //designOption.getSqlMap().put("dsf", dataScopeFilter(user.getCurrentUser(), "o", "a"));
		        // 设置分页参数
				consignmentNote.setPage(page);
				consignmentNote.setDelect(ResourcesUtil.getConfig("booking_orders"));
		        // 执行分页查询
		        page.setList(shippingFormEntityMapper.findList(consignmentNote));
		        return page;
		}
	
	
	
	/**
	 * @Title: 选择款式装箱单一览
	 * @Description: 一览查询
	 * @param page
	 * @param enchase
	 * @return Page<Enchase>
	 */
	public Page<PackageCustomEntity> findpackingList(Page<PackageCustomEntity> page, PackageCustomEntity packageCustomEntity) {
		// 设置分页参数
		packageCustomEntity.setPage(page);
		// 执行分页查询
		page.setList(packageCustomEntityMapper.findList(packageCustomEntity));
		return page;
	}
	
	/**
	 * @Title: 选择款式装箱单一览
	 * @Description: 一览查询
	 * @param page
	 * @param enchase
	 * @return Page<Enchase>
	 */
	public List<CustomEnchase> findPackageDetail(ConsignmentNote consignmentNote) {
		String idStr = consignmentNote.getIdStr();
		List<CustomEnchase> cList = new ArrayList<>();
		CustomEnchase customEnchase;
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
		if (!"".equals(idStr) && idStr != null) {
			String[] packageIdList = idStr.split(",");
			for (int i = 0; i < packageIdList.length; i++) {
				if (!"".equals(packageIdList[i]) && packageIdList[i] != null) {
					customEnchase = customEnchaseDao.get(packageIdList[i]);
					customEnchase.setId(Long.parseLong(packageIdList[i]));
					customEnchase.setTargetDateStr(simpleDateFormat.format(customEnchase.getTargetDate()));
					customEnchase.setContracts(customEnchaseDao.getContractInfo(customEnchase));
					cList.add(customEnchase);
				}
			}
		}
		return cList;
	}
	
	/**
	 * @Title: 新建订舱委托单
	 * @Description: 查询
	 * @param indentId
	 * @return BookingOrders
	 */
	public ConsignmentNote getBookingOrderByIndentId(ConsignmentNote consignmentNote) {
		ConsignmentNote bo = new ConsignmentNote();
		List<ConsignmentNote> resultBookingOrders = shippingFormEntityMapper.getBookingOrderByIndentId(consignmentNote);
		   
		if(!CollectionsUtils.isEmpty(resultBookingOrders)){
			 bo.setConsignmentNoteList(resultBookingOrders);
	    }		
		return bo;
	}

	

	
	/**
	 * check BigDecimal
	 * @param cost
	 * @return 取不到返回0
	 */
	private BigDecimal checkBigDecimalNull(BigDecimal cost) {
		if(cost==null){
			return new BigDecimal("0");
		}
		return cost;
	}

	/**
	  * @Title: saveDict
	  * @Description: 保存基准数据
	  * @param @param dict
	  * @return void 
	  * @throws
	  */
	@Transactional(readOnly = false)
	public void saveBookingOrders(ConsignmentNote consignmentNote) {
		
		// 判断新建编辑
		//若为null 执行插入语句（新建）
		if (consignmentNote.getId()==null || "".equals(consignmentNote.getId())){			
			consignmentNote.preInsert();
			consignmentNote.setVersion(1L);
			
			// 取得委托单编号
	        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm");  
	        String dateNowStr = sdf.format(new Date());  
	        consignmentNote.setFormId(consignmentNote.getOgnizationShortName() + "." + dateNowStr);
	        //设置订舱区分为定制
	        consignmentNote.setFormFlag("1");
			if(StringUtils.isEmpty(consignmentNote.getBookingordersStatus())){
				// 设置委托单状态
				consignmentNote.setBookingordersStatus(ResourcesUtil.getConfig("bookingorders_status_begin"));
			}
			shippingFormEntityMapper.insertConsignmentNote(consignmentNote);
			
		}
		//编辑
		else{
			// 更新数据
			shippingFormEntityMapper.deleteShippingDetails(consignmentNote);
			consignmentNote.preUpdate();
			shippingFormEntityMapper.update(consignmentNote);
			
		}
			// 判断list是否为空
			if(!CollectionsUtils.isEmpty(consignmentNote.getConsignmentNoteList())){
				// 遍历赋值
				Order order = null;
				Settlement settlement = new Settlement();
				settlement.setExchangeFormEntity(new ExchangeFormEntity());
				settlement.preInsert();
				SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");  
		        for(ConsignmentNote  hb : consignmentNote.getConsignmentNoteList()){
	        		//创建人信息
	        	    hb.preInsert();
	        	    hb.setVersion(1L);
	        	    hb.setId(consignmentNote.getId());
	        	    shippingFormEntityMapper.insertShippingDetails(hb);
	        	    order = orderDao.getCostByDate(hb);
	        	    if (order != null) {
	        	    	settlement.getExchangeFormEntity().setForeignNo(SequenceUtil.commonCode("E."+consignmentNote.getOgnizationShortName()+"."+sdf.format(hb.getPackageCustomEntity().getDeliveryDate())+".","sequence_exchangeForm",4).getReturnCode());
	        	    	settlement.getExchangeFormEntity().setFormId(consignmentNote.getId());
	        	    	settlement.getExchangeFormEntity().setOgnizationId(1L);
	        	    	settlement.getExchangeFormEntity().setCustomerId(Long.parseLong(consignmentNote.getOgnizationId()));
	        	    	settlement.getExchangeFormEntity().setContractId(hb.getContractCustomEntity().getContractId());
	        	    	settlement.getExchangeFormEntity().setSettlementDate(hb.getPackageCustomEntity().getDeliveryDate());
	        	    	settlement.getExchangeFormEntity().setCommission(new BigDecimal(0));
	        	    	settlement.getExchangeFormEntity().setOthers(new BigDecimal(0));
	        	    	settlement.getExchangeFormEntity().setPaymentMethod("");
	        	    	settlement.getExchangeFormEntity().setQuantity(order.getOrderQuantity());
	        	    	settlement.getExchangeFormEntity().setAmountMoney(order.getCost());
	        	    	settlement.getExchangeFormEntity().setSpecifiedAmount(order.getCost());
	        	    	settlement.getExchangeFormEntity().setSettlementStatus(ResourcesUtil.getConfig("exchange_es00"));
	        	    	exchangeFormEntityMapper.insertExchangeForm(settlement);
					}
		        }
			}
	}

	/**
	* @Title: commitBookingOrders
	* @Description: 提交发货通知单
	* @param consignmentNote
	* @return void 
	* @throws
	*/
	@Transactional(readOnly = false)
	public void commitBookingOrders(ConsignmentNote consignmentNote) {
		consignmentNote.preUpdate();
		consignmentNote.setFormStatus("1");
		shippingFormEntityMapper.commit(consignmentNote);
		
	}
	
	/**
	* @Title: deleteBookingOrders
	* @Description: 删除数据(逻辑删除)
	* @param consignmentNote
	* @return void 
	* @throws
	*/
	@Transactional(readOnly = false)
	public void deleteBookingOrders(ConsignmentNote consignmentNote) {
		// 执行逻辑删除
		shippingFormEntityMapper.delete(consignmentNote);
		// 逻辑删除结汇交汇单
		//shippingFormEntityMapper.deleteExchange(consignmentNote);
	}
	
	
	
	
    /**
     * @Title: findAuditList
     * @Description: 查询所有履历
     * @param @param auditInfo
     * @param @return
     * @return List<AuditInfo> 
     * @throws
     */
   public AuditInfo findAuditInfo(AuditInfo auditInfo) {
	   AuditInfo audit = new AuditInfo();
	   audit.setAuditList(auditInfoDao.findAllList(auditInfo));
	   audit.setAuditStatus(auditInfoDao.findAuditAcceptCount(auditInfo));
       // 执行查询
       return audit;
   }
   
   /**
    * @Title: getAuditResult
    * @Description: 审核结果
    * @param @param auditInfo
    * @param @return
    * @return 审核结果通过数
    * @throws
    */
  
  public long getAuditResult(AuditInfo auditInfo) {
	   
      return auditInfoDao.findAuditAcceptCount(auditInfo);
  }
  
  /**
	  * @Title: saveAudit
	  * @Description: 保存履历信息
	  * @param @param auditInfo
	  * @return void 
	  * @throws
	  */
	@Transactional(readOnly = false)
	public void saveAuditInfo(AuditInfo auditInfo) {
		
		 // 插入履历表
	     auditInfo.preInsert();
	     auditInfo.setAuditDate(new Date());
	     auditInfo.setAuditUserId(UserUtils.getUser().getId());
      // 新建版本号赋值1
	     auditInfo.setVersion(1L);
	     auditInfoDao.insert(auditInfo);
	     
	     // 
	     auditInfo.preUpdate();
	     shippingFormEntityMapper.updateConsignmentNoteStatus(auditInfo);
	}

	/**
	 * 查询一条采购合同信息
	 * @param user
	 * @return
	 */
	public ConsignmentNote getBooking(ConsignmentNote consignmentNote) {
	
		return shippingFormEntityMapper.get(consignmentNote);
	}
	/**
	 * ID查询信息 
	 * @param user
	 * @return
	 */
	public List<ConsignmentNote> findBookingByID(ConsignmentNote consignmentNote) {
//		 BookingOrders bo = new BookingOrders();
//		 List<BookingOrders> resultFindBooking = bookingOrdersDao.findBookingByID(bookingOrders);
//		 if(!CollectionsUtils.isEmpty(resultFindBooking)){
//			   bo.setBookingOrderList(resultFindBooking);	     		
//	      }
		 return shippingFormEntityMapper.findBookingByID(consignmentNote);
	}



	
	
	
	

	
}
